import axios, {
    AxiosError,
    AxiosResponse,
    AxiosInstance,
    AxiosRequestConfig,
} from 'axios';

import { Axios } from '../interface/index';

const config = {
    // 默认地址请求地址，可在 .env.*** 文件中修改
    baseURL: 'http://127.0.0.1:5000/',
    // 设置超时时间（10s）
    timeout: 10000,
    // 跨域时候允许携带凭证
    // withCredentials: true,
    //   headers:{'Content-Type':"application/json"}
};

class RequestHttp {
    service: AxiosInstance;
    public constructor(config: AxiosRequestConfig) {
        // 实例化axios
        this.service = axios.create(config);
        this.service.interceptors.request.use(
            (config: AxiosRequestConfig) => {
                let token = sessionStorage.getItem('token');
                return {
                    ...config,
                    headers: { ...config.headers, 'token': token },
                };
            },
            (error: AxiosError) => {
                return Promise.reject(error);
            }
        );

        this.service.interceptors.response.use(
            (response: AxiosResponse) => {
                const { data } = response;
                // if (data.code !== 200) {
                //   return Promise.reject(data);
                // }
                if (data.data?.token) {
                    sessionStorage.setItem('token', data.data.token);
                }
                return data;
            },
            async (error: AxiosError) => {
                return Promise.reject(error);
            }
        );
    }

    // * 常用请求方法封装
    get<T>(
        url: string,
        params?: any,
        _object = {}
    ): Promise<Axios.ResultData<T>> {
        return this.service.get(url, { params, ..._object });
    }
    post<T>(
        url: string,
        params: any,
        _object = {}
    ): Promise<Axios.ResultData<T>> {
        return this.service.post(url, params, _object);
    }
}

export default new RequestHttp(config);
